package com.tuanzi.loan.business.repository.xhh.settlementsystem.impl;

import com.tuanzi.loan.business.repository.xhh.settlementsystem.custom.XhhSettlementIncomeActivityRepositoryCustom;
import com.tuanzi.loan.core.repository.JOOQBaseRepositoryPlus;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;

import java.util.Date;
import java.util.List;

import static com.tuanzi.loan.generated.jooq.loan.tables.XhhLoanSettlementIncome.XHH_LOAN_SETTLEMENT_INCOME;
import static com.tuanzi.loan.generated.jooq.loan.tables.XhhLoanSettlementIncomeActivity.XHH_LOAN_SETTLEMENT_INCOME_ACTIVITY;
import static com.tuanzi.loan.generated.jooq.stat.tables.StatActivityJoin.STAT_ACTIVITY_JOIN;

/**
 * @author caiwanlin
 * @create 2018-08-20 20:23
 */
public class XhhSettlementIncomeActivityRepositoryImpl extends JOOQBaseRepositoryPlus implements XhhSettlementIncomeActivityRepositoryCustom {

    @Override
    protected TableImpl getTable() {
        return XHH_LOAN_SETTLEMENT_INCOME_ACTIVITY;
    }

    @Override
    public Integer getUv(Date startTime, Date endTime, List<Long> activityIdList) {
        Integer uv = dslContext.select(DSL.sum(STAT_ACTIVITY_JOIN.CLICK_UV).as("uv"))
                .from(STAT_ACTIVITY_JOIN)
                .where(STAT_ACTIVITY_JOIN.DATE.between(new java.sql.Date(startTime.getTime()), new java.sql.Date(endTime.getTime()))
                        .and(STAT_ACTIVITY_JOIN.ACTIVITY_ID.in(activityIdList)).and(STAT_ACTIVITY_JOIN.SPACE_ID.eq(-1000)))
                .fetchOne().get("uv",int.class);
        return uv==null?0:uv;
    }

    @Override
    public void deleteByCompanyId(Long id) {
        dslContext.delete(XHH_LOAN_SETTLEMENT_INCOME_ACTIVITY).where(XHH_LOAN_SETTLEMENT_INCOME_ACTIVITY.INCOME_ID.in(dslContext
                .select(XHH_LOAN_SETTLEMENT_INCOME.ID).from(XHH_LOAN_SETTLEMENT_INCOME).where(XHH_LOAN_SETTLEMENT_INCOME.COMPANY_ID
                        .eq(id)).fetch())).execute();
    }

    @Override
    public void deleteByProductId(Long id) {
        dslContext.delete(XHH_LOAN_SETTLEMENT_INCOME_ACTIVITY).where(XHH_LOAN_SETTLEMENT_INCOME_ACTIVITY.INCOME_ID.in(dslContext
                .select(XHH_LOAN_SETTLEMENT_INCOME.ID).from(XHH_LOAN_SETTLEMENT_INCOME).where(XHH_LOAN_SETTLEMENT_INCOME.PRODUCT_ID
                        .eq(id)).fetch())).execute();
    }
}
